<template>
  <div>
    <div style="border: 1px solid #ccc; padding: 20px; height: calc(75vh - 83px); ">
      <div style="display: flex; align-items: center; gap: 10px;">
          <!-- 扫码输入框 -->
          <el-input
              ref="scanInput"
              v-model="scanCode"
              :placeholder="pageVal.scanPlaceholder"
              @keyup.enter.native="handleScanFixture"
              clearable
              style="flex: 1;">
          </el-input>
          <!-- 保存点检结果 -->
          <el-button type="primary" @click="saveFixtureCheckResult">
            {{ pageVal.saveResult }}
          </el-button>
          <!-- 重新扫描 -->
          <el-button @click="resetScan" style="margin-right: 10px">
            {{ pageVal.scanAgain }}
          </el-button>
      </div>
      <div  style="display: flex; align-items: center; gap: 10px; margin-top: 12px">
        <!-- 点检人 -->
        <span>{{pageVal.fixtureChecklist.check_person}}：</span>
        <el-input
            ref="checkPerson"
            v-model="checkPerson"
            clearable
            style="width: 200px ">
        </el-input>
        <!-- 点检日期 -->
        <span>{{pageVal.fixtureChecklist.check_date}}：</span>
        <el-date-picker
            v-model="checkDate"
            type="datetime"
            :placeholder="main.selectDate"
            value-format="yyyy-MM-dd HH:mm:ss"
            :default-time="defaultTime"
            @change="confirmDateTime"
            style="width: 200px"/>
        <!-- 点检班次 -->
        <span>{{pageVal.fixtureChecklist.check_shift}}：</span>
        <el-select
            v-model="checkShift"
            :placeholder="main.selectShift"
            style="width: 230px">
          <el-option
              v-for="item in shiftOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
      </div>
      <el-table
          :data="fixtureChecklistData"
          style="width: 80vw; margin-top: 12px"
          :height="fixtureInspectionManagementHeight"
          border
          highlight-current-row>
        <!-- 序号 -->
        <el-table-column
            :label="pageVal.fixtureChecklist.order"
            width="60"
            align="center"
            v-slot:default="scope">
          {{scope.$index+1}}
        </el-table-column>
        <!-- 检查项目 -->
        <el-table-column
            :label="pageVal.fixtureChecklist.measurement_project"
            align="center"
            v-slot:default="scope">
                            <span v-if="languageS==='chinese' && scope.row.measurement_project!==undefined && scope.row.measurement_project.split('|*|').length===3">
                              {{scope.row.measurement_project.split('|*|')[0]}}</span>
          <span v-else-if="languageS==='english' && scope.row.measurement_project!==undefined && scope.row.measurement_project.split('|*|').length===3">
                              {{scope.row.measurement_project.split('|*|')[1]}}</span>
          <span v-else-if="languageS==='russian' && scope.row.measurement_project!==undefined && scope.row.measurement_project.split('|*|').length===3">
                              {{scope.row.measurement_project.split('|*|')[2]}}</span>
          <span v-else>{{scope.row.measurement_project}}</span>
        </el-table-column>
        <!-- 检查标准 -->
        <el-table-column
            :label="pageVal.fixtureChecklist.measurement_standard"
            align="center"
            v-slot:default="scope">
                            <span v-if="languageS==='chinese' && scope.row.measurement_standard!==undefined && scope.row.measurement_standard.split('|*|').length===3">
                              {{scope.row.measurement_standard.split('|*|')[0]}}</span>
          <span v-else-if="languageS==='english' && scope.row.measurement_standard!==undefined && scope.row.measurement_standard.split('|*|').length===3">
                              {{scope.row.measurement_standard.split('|*|')[1]}}</span>
          <span v-else-if="languageS==='russian' && scope.row.measurement_standard!==undefined && scope.row.measurement_standard.split('|*|').length===3">
                              {{scope.row.measurement_standard.split('|*|')[2]}}</span>
          <span v-else>{{scope.row.measurement_standard}}</span>
        </el-table-column>
        <!-- 评价/测量技术 -->
        <el-table-column
            :label="pageVal.fixtureChecklist.measurement_technique"
            align="center"
            width="130"
            v-slot:default="scope">
          <span v-if="languageS==='chinese' && scope.row.measurement_technique!==undefined && scope.row.measurement_technique.split('/').length===3">
            {{scope.row.measurement_technique.split('/')[0]}}</span>
          <span v-else-if="languageS==='english' && scope.row.measurement_technique!==undefined && scope.row.measurement_technique.split('/').length===3">
            {{scope.row.measurement_technique.split('/')[1]}}</span>
          <span v-else-if="languageS==='russian' && scope.row.measurement_technique!==undefined && scope.row.measurement_technique.split('/').length===3">
            {{scope.row.measurement_technique.split('/')[2]}}</span>
          <span v-else>{{scope.row.measurement_technique}}</span>
        </el-table-column>
        <!-- 周期 -->
        <el-table-column
            :label="pageVal.fixtureChecklist.cycle"
            width="100"
            align="center">
        </el-table-column>
        <!-- 点检结果 -->
        <el-table-column
            :label="pageVal.fixtureChecklist.check_result"
            width="100"
            align="center">
          <template #default="scope">
            <el-radio-group v-model="scope.row.check_result" style="text-align: left">
              <el-radio label="YES" style="margin-bottom: 10px">YES</el-radio>
              <el-radio label="NO" style="margin-bottom: 10px">NO</el-radio>
            </el-radio-group>
            <el-button
                size="mini"
                @click="scope.row.check_result = ''">
              {{pageVal.cancel}}
            </el-button>
          </template>
        </el-table-column>
        <!-- 点检值 -->
        <el-table-column
            :label="pageVal.fixtureChecklist.check_value"
            width="100"
            align="center"
            v-slot:default="scope">
          <el-input
              v-model="scope.row.check_value"
              v-if="scope.row.measurement_type==='测量/Measurement/Измерение'">
          </el-input>
        </el-table-column>
        <!-- 异常描述 -->
        <el-table-column
            :label="pageVal.fixtureChecklist.abnormal_description"
            width="150"
            align="center"
            v-slot:default="scope">
          <el-input
              v-model="scope.row.abnormal_description"
              type="textarea"
              :rows="3"
              :placeholder="pageVal.inputAbnormalDescription"
              v-if="scope.row.check_result==='NO'">
          </el-input>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { debounce } from 'lodash';
export default {
  // 通过 props 接收当前激活的 tab
  props: {
    activeTab: {
      type: String,
      default: ''
    }
  },
  data(){
    return {
      //控制工装点检管理高度的变量
      fixtureInspectionManagementHeight:window.visualViewport.height-390,
      //—————————————————————————————————————————基本信息变量————————————————————————————————————————————
      //用户权限相关的变量
      useName:'',//用户名称
      useId:'',//用户编号
      usePower:'',//用户权限
      //用户登录后默认为中文
      languageS:'chinese',
      //切换语言，页面变量
      main:{
        edit:'编辑',
        select:'请选择',
        selectDate:'选择日期',
        selectShift:'选择班次',
        chinese:'中文',
        english:'英文',
        russian:'俄文',
      },
      pageVal:{
        translate:'自动翻译',
        cancel:'取 消',
        ok:'确 定',
        sureToDelete:'确定删除数据吗？',
        scanPlaceholder:'请扫描二维码或手动输入编号',
        inputAbnormalDescription:'请输入异常描述',
        saveResult:'保存点检结果',
        scanAgain:'重新扫描',
        scanning:'正在处理...',
        fixtureChecklist:{
          check_person:'点检人',
          check_date:'点检日期',
          check_shift:'点检班次',
          order:'序号',
          measurement_project:'检查项目',
          measurement_standard:'检查标准',
          measurement_technique:'评价/测量技术',
          cycle:'周期',
          check_result:'点检结果',
          check_value:'点检值',
          abnormal_description:'异常描述',
        },
      },

      //工装点检管理
      fixtureChecklistData:[
        {
          //唯一标识，低代码的主键
          id:'',
          //创建时间
          create_time:'',
          //更新时间
          update_time:'',
          //创建人
          creator:'',
          //流程状态
          process_status:'',
          //更新人
          sys_update_user:'',
          //审核人
          sys_audit_user:'',
          //审核时间
          sys_audit_time:'',
          //逻辑删除
          sys_deleted:'',

          //车间
          workshop:'',
          //责任部门
          department:'',
          //机床名称
          equipment_name:'',
          //线体
          line:'',
          //工序或存放地点
          op:'',
          //检查项目
          measurement_project:'',
          //图纸编号
          drawing_number:'',
          //检查标准
          measurement_standard:'',
          //测量类型
          measurement_type:'',
          //标准值
          standard_value:'',
          //上公差
          upper_tolerance:'',
          //下公差
          lower_tolerance:'',
          //机型
          model:'',
          //评价测量技术
          measurement_technique:'',
          //周期
          cycle:'',
          //工装编号
          fixture_number:'',
          //点检结果
          check_result:'',
          //点检值
          check_value:'',
          //异常描述
          abnormal_description:'',
          //点检日期
          check_date:'',
          //点检班次
          check_shift:'',
          //点检人
          check_person:'',
          //指导书id
          instruction_id:'',
        }
      ],
      //工装点检管理
      fixtureChecklistForm:{
        //唯一标识，低代码的主键
        id:'',
        //创建时间
        create_time:'',
        //更新时间
        update_time:'',
        //创建人
        creator:'',
        //流程状态
        process_status:'',
        //更新人
        sys_update_user:'',
        //审核人
        sys_audit_user:'',
        //审核时间
        sys_audit_time:'',
        //逻辑删除
        sys_deleted:'',

        //车间
        workshop:'',
        //责任部门
        department:'',
        //机床名称
        equipment_name:'',
        //线体
        line:'',
        //工序或存放地点
        op:'',
        //检查项目
        measurement_project:'',
        //图纸编号
        drawing_number:'',
        //检查标准
        measurement_standard:'',
        //测量类型
        measurement_type:'',
        //标准值
        standard_value:'',
        //上公差
        upper_tolerance:'',
        //下公差
        lower_tolerance:'',
        //机型
        model:'',
        //评价测量技术
        measurement_technique:'',
        //周期
        cycle:'',
        //工装编号
        fixture_number:'',
        //点检结果
        check_result:'',
        //点检值
        check_value:'',
        //异常描述
        abnormal_description:'',
        //点检日期
        check_date:'',
        //点检班次
        check_shift:'',
        //点检人
        check_person:'',
        //指导书id
        instruction_id:'',
      },

      scanCode: '',       // 存储扫描/输入的二维码内容
      scanLoading: false, // 加载状态
      scanResult: null, // 存储扫描结果
      instructionDataList: [], // 存储查询到的作业指导书数据

      defaultTime: new Date(), // 默认时间（当前时间）

      //修改点检人的变量
      checkPerson: null,
      //修改点检日期的变量
      checkDate: null,
      //修改点检班次的变量
      checkShift:null,
      //班次选择选项
      shiftOptions: [
        {value: '早班/morning Shift/Ранняя смена', label: '早班/morning Shift/Ранняя смена'},
        {value: '中班/middle shift/Средний класс', label: '中班/middle shift/Средний класс'},
        {value: '夜班/night shift/Ночная работа', label: '夜班/night shift/Ночная работа'}
      ],
    }
  },
  created() {
    // 初始化时设置默认时间为当前时间（确保是字符串）
    const now = new Date();
    this.checkDate = this.formatDateTime(now);
    // 同时赋值给 check_date
    this.fixtureChecklistData.check_date = this.checkDate;
  },
  watch: {
    activeTab(newVal) {
      if (newVal === 'fixtureInspectionManagement') {
        this.focusInput();
      }
    }
  },
  methods:{
    //查询用户信息的函数
    inquiry(){
      //输入用户编号，向后端查询信息
      const useId=localStorage.getItem('userName').replace(/"/g, '');
      this.$request.post('/useQueryPower',{
        queryFiledName:'goodProductCondition',
        userId:useId,
      }).then(result=>{
        if (result.code === 401) {
          this.$router.push('UserLogin')
          alert("您未登录，请登录")
        }else {
          this.useName=result.data.name
          this.usePower=result.data.goodProductCondition
          this.useId=useId
        }
      })
    },
    //选择语言
    changeLanguage(language){
      this.languageS=language
      // 其他语言切换逻辑...
      this.componentKey = !this.componentKey;
      if (language==='chinese'){
        //main
        this.main.edit='编辑'
        this.main.select='请选择'
        this.main.selectDate='选择日期'
        this.main.selectShift='选择班次'
        this.main.chinese='中文'
        this.main.english='英文'
        this.main.russian='俄文'
        //pageVal
        this.pageVal.translate='自动翻译'
        this.pageVal.cancel='取 消'
        this.pageVal.ok='确 定'
        this.pageVal.sureToDelete='确定删除数据吗？'
        this.pageVal.scanPlaceholder='请扫描二维码或手动输入编号'
        this.pageVal.inputAbnormalDescription='请输入异常描述'
        this.pageVal.saveResult='保存点检结果'
        this.pageVal.scanAgain='重新扫描'
        this.pageVal.scanning='正在处理...'

        this.pageVal.fixtureChecklist.check_person='点检人'
        this.pageVal.fixtureChecklist.check_date='点检日期'
        this.pageVal.fixtureChecklist.check_shift='点检班次'
        this.pageVal.fixtureChecklist.order='序号'
        this.pageVal.fixtureChecklist.measurement_project='检查项目'
        this.pageVal.fixtureChecklist.measurement_standard='检查标准'
        this.pageVal.fixtureChecklist.measurement_technique='评价/测量技术'
        this.pageVal.fixtureChecklist.cycle='周期'
        this.pageVal.fixtureChecklist.check_result='点检结果'
        this.pageVal.fixtureChecklist.check_value='点检值'
        this.pageVal.fixtureChecklist.abnormal_description='异常描述'
      }
      else if (language==='english') {
        //main
        this.main.edit='Edit'
        this.main.select='Select'
        this.main.selectDate='Select Date'
        this.main.selectShift='Select Shift'
        this.main.chinese='Chinese'
        this.main.english='English'
        this.main.russian='Russian'
        //pageVal
        this.pageVal.translate='Automatic translation'
        this.pageVal.cancel='Cancel'
        this.pageVal.ok='OK'
        this.pageVal.sureToDelete='Sure to delete the data?'
        this.pageVal.scanPlaceholder='Please scan the QR code or manually enter the number'
        this.pageVal.inputAbnormalDescription='Enter Abnormal Description'
        this.pageVal.saveResult='Save'
        this.pageVal.scanAgain='Rescan'
        this.pageVal.scanning='Scanning'

        this.pageVal.fixtureChecklist.check_person='Checked By'
        this.pageVal.fixtureChecklist.check_date='Date of Check'
        this.pageVal.fixtureChecklist.check_shift='Work Shift'
        this.pageVal.fixtureChecklist.order='Order'
        this.pageVal.fixtureChecklist.measurement_project='Measurement Project'
        this.pageVal.fixtureChecklist.measurement_standard='Measurement Standard'
        this.pageVal.fixtureChecklist.measurement_technique='Measurement Technique'
        this.pageVal.fixtureChecklist.cycle='Cycle'
        this.pageVal.fixtureChecklist.check_result='Check Result'
        this.pageVal.fixtureChecklist.check_value='Check Value'
        this.pageVal.fixtureChecklist.abnormal_description='Abnormal Description'
      }
      else if (language==='russian') {
        //main
        this.main.edit='Правка'
        this.main.select='Выберите'
        this.main.selectDate='Выберите дату'
        this.main.selectShift='Выберите смену'
        this.main.chinese='Китайский'
        this.main.english='Aнглийский'
        this.main.russian='Русский'
        //pageVal
        this.pageVal.translate='Автоматический перевод'
        this.pageVal.cancel='Отмена'
        this.pageVal.ok='Подтвердить'
        this.pageVal.sureToDelete='Уверен в удалении данных?'
        this.pageVal.scanPlaceholder='Сканируйте QR-код или введите номер вручную'
        this.pageVal.inputAbnormalDescription='Введите аномальное описание'
        this.pageVal.saveResult='Сохранить'
        this.pageVal.scanAgain='Пересканирование'
        this.pageVal.scanning='Сканирование'

        this.pageVal.fixtureChecklist.check_person='Проверил'
        this.pageVal.fixtureChecklist.check_date='Дата проверки'
        this.pageVal.fixtureChecklist.check_shift='Смена проверки'
        this.pageVal.fixtureChecklist.order='Заказ'
        this.pageVal.fixtureChecklist.measurement_project='Проект'
        this.pageVal.fixtureChecklist.measurement_standard='Стандарт проверки'
        this.pageVal.fixtureChecklist.measurement_technique='Технология оценки/измерения'
        this.pageVal.fixtureChecklist.cycle='Цикл'
        this.pageVal.fixtureChecklist.check_result='Проверьте результат'
        this.pageVal.fixtureChecklist.check_value='Проверьте стоимость'
        this.pageVal.fixtureChecklist.abnormal_description='Абнормальное описание'
      }
    },
    //通用：得到UUID的id数据
    generateUUIDv4() {
      const bytes = new Uint8Array(16);
      crypto.getRandomValues(bytes);

      // 设置版本位（第6字节的高4位为0100）
      bytes[6] = (bytes[6] & 0x0f) | 0x40;
      // 设置变体位（第8字节的高2位为10）
      bytes[8] = (bytes[8] & 0x3f) | 0x80;

      // 转换为32字符十六进制字符串
      return Array.from(bytes, byte => {
        return byte.toString(16).padStart(2, '0');
      }).join('');
    },
    // 格式化日期时间为 localDateTime 格式 (yyyy-MM-dd HH:mm:ss)
    formatDateTime(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    //依据用户现在的是哪一种作业指导书，筛选出所有的数据来,改造成带有返回值的函数
    async inquiryType(type){
      const result= await this.$request.post('/inquiryType',type)
      if (result.code === 401) {
        this.$router.push('UserLogin')
        alert("您未登录，请登录")
      } else {
        return result.data
      }
    },
    //查询低频作业指导书中"工装点检"
    queryInstructionId(){
      // 先清空现有数据
      this.fixtureChecklistData = [];
      this.inquiryType('工装点检').then(dataList => {
        // 筛选 workshop 为 '装配车间/Assembly workshop/Сборочная линия' 的数据
        const filteredList = dataList.filter(data =>
            data.workshop === '装配车间/Assembly workshop/Сборочная линия'
        );

        // 保存到 instructionDataList 供后续查找使用
        this.instructionDataList = filteredList;
      });
    },
    //校验输入是否为数值
    isValidNumberStrict(value) {
      // 排除 null、undefined、空字符串
      if (value === null || value === undefined || value === '') return false;

      // 转换为字符串（防止 Number 类型直接通过）
      const strValue = String(value).trim();

      // 正则表达式：可选正负号 + 数字 + 可选小数点 + 数字
      const regex = /^[-+]?\d*\.?\d+$/;

      return regex.test(strValue);
    },

    // 处理扫描/输入
    //添加防抖处理 debounce(function())
    handleScanFixture: debounce(async function() {
      if (!this.scanCode.trim()) {
        const messages = {
          chinese: '请扫描二维码或手动输入ID',
          english: 'Please scan the QR code or manually enter the ID',
          russian: 'Сканируйте QR-код или введите ID вручную',
        };
        this.$message.warning(messages[this.languageS]);
        return;
      }

      this.scanLoading = true;
      try {
        const instructionId = this.scanCode.trim();

        // 1. 直接从 instructionDataList 中查找对应的作业指导书数据
        const instructionData = this.instructionDataList.filter(data =>
            data.id === instructionId || data.id.toString() === instructionId
        );

        if (!instructionData || instructionData.length === 0) {
          const messages = {
            chinese: '未找到对应的作业指导书，请检查ID是否正确',
            english: 'No corresponding work instruction found, please check if the ID is correct',
            russian: 'Соответствующая рабочая инструкция не найдена, проверьте правильность ID',
          };
          this.$message.error(messages[this.languageS]);
          return;
        }

        const data = instructionData[0];

        // 2. 解析workBook字段
        let checkItems = [];
        if (data.workBook && typeof data.workBook === 'string') {
          // 先以 '|-|' 切分，得到若干行数据
          const workBookRows = data.workBook.split('|-|').filter(row => row.trim());

          // 对每一行数据再以 '|%|' 切分
          checkItems = workBookRows.map((row, index) => {
            const rowData = row.split('|%|');
            return {
              id: `${data.id}_${index}`, // 生成唯一ID
              instruction_id: data.id, // 关联的作业指导书ID
              measurement_project: data.fileName, // 检查项目
              measurement_standard: rowData[0] || '', // 检查标准
              measurement_technique: rowData[5] || '', // 评价测量技术
              cycle: rowData[6] || '', // 周期
              check_result: '', // 点检结果
              check_value: '', // 点检值
              abnormal_description: '', // 异常描述
              row_index: index // 行索引
            };
          });
        }

        // 3. 更新扫描详情
        this.scanDetailsFixture = {
          instruction_id: data.id,
          number: data.id, // 使用ID作为编号
          workshop: data.workshop,
          line: data.lineName,
          op: data.op
        };

        // 4. 更新表格数据
        this.fixtureChecklistData = checkItems;

        // 5. 成功提示和焦点转移
        const successMessages = {
          chinese: 'ID验证成功，请填写点检信息',
          english: 'ID verification successful, please fill in the inspection information',
          russian: 'Проверка ID успешна, пожалуйста, заполните информацию об инспекции',
        };
        this.$message.success(successMessages[this.languageS]);

        this.$nextTick(() => {
          this.focusOnResultArea();
        });
      } catch (error) {
        this.$message.error(error.message || '处理ID失败');
      } finally {
        this.scanLoading = false;
      }
    }, 300),
    // 将焦点转移到结果区域
    focusOnResultArea() {
      if (this.$refs.resultArea) {
        this.$refs.resultArea.focus();
      }
    },
    // 弹窗打开后自动聚焦输入框
    focusInput() {
      this.$nextTick(() => {
        if (this.$refs.scanInput) {
          this.$refs.scanInput.focus();
        }
      });
    },
    //修改点检日期
    confirmDateTime(newDateTime) {
      if (newDateTime) {
        console.log("选择的日期时间:", newDateTime);
        // 更新 check_time 为新选择的日期
        this.fixtureChecklistData.check_time = newDateTime;
      } else {
        // 如果用户清空了选择器，可以恢复为当前时间或做其他处理
        const now = new Date();
        this.selectedDateTime = this.formatDateTime(now);
        this.fixtureChecklistData.check_time = this.selectedDateTime;
      }
    },
    //保存工装点检结果
    saveFixtureCheckResult() {
      //校验点检人
      if (this.checkPerson==='' || this.checkPerson===undefined || this.checkPerson===null){
        if(this.languageS==='chinese'){
          this.$message.error('您未输入"点检人"，请输入')
        }
        else if(this.languageS==='english'){
          this.$message.error('Please enter the "Check person"')
        }
        else if(this.languageS==='russian'){
          this.$message.error('Пожалуйста, введите "Проверьте человека"')
        }
        return
      }
      //校验点检班次
      if (this.checkShift==='' || this.checkShift===undefined || this.checkShift===null){
        if(this.languageS==='chinese'){
          this.$message.error('您未输入"点检班次"，请输入')
        }
        else if(this.languageS==='english'){
          this.$message.error('Please enter the "Check shift"')
        }
        else if(this.languageS==='russian'){
          this.$message.error('Пожалуйста, введите "Проверьте смену"')
        }
        return
      }
      // 给后端发送的数据
      let fixtureChecklist = [];

      // 过滤掉用户没有填写的行
      let filterFixtureChecklistData = this.fixtureChecklistData.filter(item =>
          (item.check_result !== null && item.check_result !== '' && item.check_result !== undefined) ||
          (item.check_value !== null && item.check_value !== '' && item.check_value !== undefined) ||
          (item.abnormal_description !== null && item.abnormal_description !== '' && item.abnormal_description !== undefined)
      );

      if (filterFixtureChecklistData.length === 0) {
        const messages = {
          chinese: '请至少填写一项点检结果',
          english: 'Please fill in at least one inspection result',
          russian: 'Пожалуйста, заполните хотя бы один результат проверки',
        };
        this.$message.warning(messages[this.languageS]);
        return;
      }

      // 确保 check_time 是最新的
      const checkTime = this.checkDate || this.formatDateTime(new Date());

      for (let i = 0; i < filterFixtureChecklistData.length; i++) {
        const item = filterFixtureChecklistData[i];
        // 数据校验
        // 如果点检结果为NO，异常描述未填，需校验
        if (item.check_result === 'NO' && (!item.abnormal_description || item.abnormal_description.trim() === '')) {
          const messages = {
            chinese: '您未输入"异常描述"，请输入',
            english: 'Please enter the "abnormal description"',
            russian: 'Пожалуйста, введите "аномальное описание"',
          };
          this.$message.error(messages[this.languageS]);
          return;
        }
        //当测量类型为计量时，如果点检值未填写，需校验
        if(item.measurement_technique==='测量/Measurement/Измерение'){
          if(item.check_value===null || item.check_value==='' ||item.check_value===undefined){
            if (this.languageS==='chinese'){
              this.$message.error('您未输入"点检值"，请输入')
            }
            else if (this.languageS==='english'){
              this.$message.error('Please enter the "check value"')
            }
            else if (this.languageS==='russian'){
              this.$message.error('Пожалуйста, введите "проверить значение"')
            }
            return
          }
          //如果点检值不是数值，需校验
          else if (!this.isValidNumberStrict(item.check_value)){
            if (this.languageS==='chinese'){
              this.$message.error('点检值非数值，请修改')
            }
            else if (this.languageS==='english'){
              this.$message.error('The check value is not a numerical value, please modify it')
            }
            else if (this.languageS==='russian'){
              this.$message.error('Значение проверки не является цифровым значением, пожалуйста, измените его')
            }
            return
          }
        }

        // 组合数据
        let temp = {
          id: this.generateUUIDv4(),
          creator: this.useName + "/" + this.useId,
          sys_deleted: 0,
          line: this.scanDetailsFixture.line,
          op: this.scanDetailsFixture.op,
          workshop:this.scanDetailsFixture.workshop,
          department:this.scanDetailsFixture.workshop,
          equipment_name:'',
          measurement_project:item.measurement_project,
          drawing_number:'',
          measurement_standard:item.measurement_standard,
          measurement_type:'',
          standard_value:'',
          upper_tolerance:'',
          lower_tolerance:'',
          model:'',
          measurement_technique: item.measurement_technique,
          cycle: item.cycle,
          fixture_number:'',
          check_result: item.check_result,
          check_value: item.check_value,
          abnormal_description: item.abnormal_description,
          check_person: this.checkPerson || this.useName,
          check_date: checkTime,
          check_shift: this.checkShift,
          instruction_id:item.instruction_id,
        };
        fixtureChecklist.push(temp);
      }

      // 保存点检结果
      this.$request.post('/insertFixtureChecklistGoodProduct', fixtureChecklist).then(result => {
        if (result.code === 401) {
          this.$router.push('UserLogin');
          alert("您未登录，请登录");
        } else {
          const messages = {
            chinese: '点检结果保存成功',
            english: 'Saved successfully',
            russian: 'Успешно сохранено',
          };
          this.$message.success(messages[this.languageS]);

          // 保存成功后重置
          this.resetAfterSave();
          // 焦点回到输入框
          this.$nextTick(() => {
            this.focusInput();
          });
        }
      }).catch(error => {
        console.error('保存失败:', error);
        this.$message.error('保存失败');
      });
    },

    // 保存后重置
    resetAfterSave() {
      this.fixtureChecklistData = [];
      this.scanCode = '';
      this.checkDate = this.formatDateTime(new Date());
      this.checkPerson = '';
      this.checkShift = '';
      this.scanDetailsFixture = {};
    },
    // 重置扫描状态
    resetScan() {
      this.fixtureChecklistData = [];
      this.scanCode = '';
      this.checkDate = this.formatDateTime(new Date());
      this.checkPerson = '';
      this.checkShift = '';
      this.scanDetailsFixture = {};

      // 焦点回到输入框
      this.$nextTick(() => {
        this.focusInput();
      });
    },
  },
  mounted() {
    this.inquiry()
    this.queryInstructionId()
  }
}
</script>

<style scoped>

</style>